import { PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Divider, message, Modal } from 'antd';
import type { SorterResult } from 'antd/es/table/interface';
import React, { useRef, useState } from 'react';
import type {
  AuthPermission,
  AuthPermissionAddItem,
  AuthPermissionEditItem,
  AuthPermissionTableListItem,
} from './data';
import {
  addAdminAccess,
  editPermission,
  getPermission,
  queryAdminAccessList,
  removePermission,
} from './service';
import AddFrom from './components/AuthPermissionAddForm';
import AuthPermissionEditForm from './components/AuthPermissionEditForm';

const TableList: React.FC<{}> = () => {
  const [sorter, setSorter] = useState<string>('');
  const [addModalVisible, handleAddModalVisible] = useState<boolean>(false);
  const [editModalVisible, handleEditModalVisible] = useState<boolean>(false);
  const [detailItemId, setDetailItemId] = useState<string | undefined>(undefined);

  const actionRef = useRef<ActionType>();

  async function handleAdd(fields: AuthPermissionAddItem) {
    const hide = message.loading('正在添加');
    try {
      const res = await addAdminAccess(fields);
      hide();
      if (res.code == 0) {
        message.success('添加成功');
        handleAddModalVisible(false);
        actionRef.current?.reload();
        return true;
      } else {
        message.error(`${res.message}`);
        return false;
      }
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      handleAddModalVisible(false);
      return false;
    }
  }

  async function handleEdit(fields: AuthPermissionEditItem) {
    const hide = message.loading('正在修改');
    try {
      // @ts-ignore
      const res = await editPermission(fields);

      hide();
      if (res == true) {
        message.success('修改成功');
        handleEditModalVisible(false);
        actionRef.current?.reload();
        return true;
      }
      message.error(`${res.message}`);
      return false;
    } catch (error) {
      hide();
      message.error('修改失败请重试！');
      handleEditModalVisible(false);
      return false;
    }
  }

  async function handleRemove(fields: AuthPermission) {
    const hide = message.loading('正在删除');
    try {
      const res = await removePermission(fields);
      hide();

      if (res == true) {
        message.success('删除成功');
        handleEditModalVisible(false);
        actionRef.current?.reload();
        return true;
      }

      message.error(`${res.message}`);
      return false;
    } catch (error) {
      hide();
      message.error('删除失败请重试！');
      handleEditModalVisible(false);
      return false;
    }
  }

  const columns: ProColumns<AuthPermissionTableListItem>[] = [
    {
      title: '权限名称',
      dataIndex: 'name',
    },
    {
      title: '权限识别码',
      dataIndex: 'code',
      hideInSearch: true,
    },
    {
      title: '权限描述',
      dataIndex: 'desc',
      hideInSearch: true,
    },
    {
      title: '操作',
      hideInSearch: true,
      render: (_, record) => {
        const onClickEdit = async () => {
          handleEditModalVisible(true);
          setDetailItemId(record.id);
        };

        const onClickRemove = () => {
          const { id, name } = record;
          Modal.confirm({
            title: `删除权限字典`,
            content: (
              <>
                <Divider />
                <p>确认要删除权限字典</p>
                <span style={{ fontWeight: 'bolder' }}>{name}</span>&nbsp;&nbsp;?
              </>
            ),
            okText: '确定',
            cancelText: '取消',
            onOk: async () => {
              await handleRemove({ id });
            },
            centered: true,
            width: '30vw',
            style: { height: '18vw' },
          });
        };

        return (
          <div>
            <a onClick={onClickEdit}>修改</a>
            <Divider type="vertical" />
            <a onClick={onClickRemove}>删除</a>
          </div>
        );
      },
    },
  ];

  return (
    <PageHeaderWrapper>
      <ProTable<AuthPermissionTableListItem>
        headerTitle="权限列表"
        actionRef={actionRef}
        rowKey="id"
        scroll={{ x: true }}
        search={{
          labelWidth: 'auto',
          span: { xs: 24, sm: 12, md: 8, lg: 8, xl: 8, xxl: 6 },
        }}
        pagination={{
          defaultPageSize: 10,
          size: 'default',
          showQuickJumper: true,
          showSizeChanger: true,
        }}
        onChange={(_, _filter, _sorter) => {
          const sorterResult = _sorter as SorterResult<AuthPermissionTableListItem>;
          if (sorterResult.field) {
            setSorter(`${sorterResult.field}_${sorterResult.order}`);
          }
        }}
        params={{
          sorter,
        }}
        toolBarRender={() => [
          <Button type="primary" onClick={() => handleAddModalVisible(true)}>
            <PlusOutlined /> 添加
          </Button>,
        ]}
        tableAlertRender={() => false}
        request={(params = {}) => {
          return queryAdminAccessList(params);
        }}
        columns={columns}
        rowSelection={false}
      />
      {editModalVisible && detailItemId && (
        <AuthPermissionEditForm
          ruleId={detailItemId}
          request={async (id) => {
            const data = await getPermission({ id });
            if (data) {
              return { success: true, data };
            }
            return { success: false, data: null };
          }}
          modalVisible={editModalVisible}
          onSubmit={(value: AuthPermissionEditItem) => handleEdit(value)}
          onCancel={() => handleEditModalVisible(false)}
        />
      )}
      {addModalVisible && (
        <AddFrom
          modalVisible={addModalVisible}
          onSubmit={(value) => handleAdd(value)}
          onCancel={() => handleAddModalVisible(false)}
        />
      )}
    </PageHeaderWrapper>
  );
};

export default TableList;
